<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">  
    <title>用户管理</title>
    <jsp:include page="../common/partial/css.jsp"></jsp:include>
  </head>  
<body>
	<div class="container col-md-12" id="userDiv">
		<jsp:include page="../common/partial/top.jsp"></jsp:include>
		<div class="row clearfix">
			<div class="col-md-12 column">
				<div class="row clearfix">
					<div class="col-md-2 column">
						<div class="list-group">
							<a href="javascript:;" class="list-group-item active"> <span class="glyphicon glyphicon-list"></span> 用户列表</a> 
							<a href="javascript:;" role="button" data-toggle="modal" data-target="#addModal" class="list-group-item"> <span class="glyphicon glyphicon-plus"></span> 新建用户</a>
						</div>
					</div>
					<div class="col-md-10 column">
						<div>
							<ol class="breadcrumb">
								<li><a href="Home/Index">首页</a></li>
								<li><a href="User/Index">用户管理</a></li>
								<li class="active">用户列表</li>
							</ol>
							<div class="alert alert-dismissible fade in" role="alert">
					            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
								<div class="panel panel-info">
				                    <div class="panel-heading">
				                        <h3 class="panel-title">友情提示</h3>
				                    </div>
				                    <div class="panel-body">
				                       	 亲，记得要至少保留一个“用户账号”。你懂的！
				                    </div>
				                </div> 
					        </div>
							<a href="" class="btn btn-default" role="button" data-toggle="modal" data-target="#addModal"><span class="glyphicon glyphicon-plus"></span> 新建用户</a> 
							<span style="padding-left: 50px;">搜索：</span> 
							<span> 
								<input type="text" placeholder="请输入用户名称搜索" v-model="searchName" class="form-control" style="width:250px; line-height:17px;display:inline-block" />
								<button class="btn btn-default" v-on:click="search">查询</button>
							</span>
						</div>
						<table id="table" class="table table-hover table-striped">
							<thead>
								<tr>
									<th>序号</th>
									<th>用户名称</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
								<tr v-for="(user,userIndex) in users">
									<th scope="row"><input type="checkbox" name="id[]" v-bind:value="user.id"/>&nbsp;{{ userIndex+1 }}</th>
									<td>
										<a href="javascript:void(0)" data-toggle="tooltip" v-bind:title="['账户密码： '+user.password]" v-on:mouseenter="toggleY">{{user.username}}</a>
									</td>
									<td>
										<div role="presentation" class="dropdown">
											<button class="btn btn-default dropdown-toggle" data-toggle="dropdown"  role="button" aria-haspopup="true" aria-expanded="false">操作 <span class="caret"></span> </button>
											<ul class="dropdown-menu">
												<li><a href="javascript:void(0)" v-on:click="editInfo(userIndex+1)">编辑</a></li>
												<li><a href="javascript:void(0)" v-on:click="del(user.id)">删除</a></li>
												<li><a href="javascript:void(0)" v-on:click="reset(user.id)">重置密码</a></li>
											</ul>
										</div>
									</td>
								</tr>
					            <tr>
				                    <th scope="row" colspan="3" v-show="this.count > 1">
				                        <input type="checkbox" id="checkall" value="" />&nbsp;&nbsp;<label for="checkall">全选</label>&nbsp;&nbsp;&nbsp;&nbsp;
				                        <a href="javascript:void(0)" class="btn btn-default" style="padding:5px 15px;" onclick="DelSelect()">批量删除</a>
				                    </th>
					            </tr>								
							</tbody>
						</table>
						<!-- 由于数据太多，所以必须以分页的形式存在 -->
						<nav aria-label="Page navigation" v-if="totalPage > 1">
							<ul class="pagination">
								<li v-bind:class="{ disabled: currentPage == 1}" v-on:click="changePage(currentPage - 1)"><a href="javascript:void(0)" aria-label="Previous"> <span aria-hidden="true">上一页</span></a></li>
								<li v-if="totalPage > 10 && currentPage >= 6" v-on:click="changePage(1)"><a href="javascript:void(0)">1</a></li>
								<li v-if="totalPage > 10 && currentPage >= 6" class="disabled"> <a href="javascript:void(0)">...</a></li>
								<li v-if="(totalPage <= 10 ) || (currentPage <= 5 && p <= 8) || (currentPage >= totalPage - 5 && p > totalPage - 8) || (currentPage > 5 && currentPage <= totalPage - 5 && p > currentPage - 3 && p < currentPage + 4)" v-for="p in totalPage" v-bind:class="{active: p == currentPage}" v-on:click="changePage(p)"><a href="javascript:void(0)" v-text="p"></a></li>
								<li v-if="totalPage > 10 && currentPage < totalPage - 5" class="disabled"><a href="javascript:void(0)">...</a></li>
								<li v-if="totalPage > 10 && currentPage < totalPage - 5" v-on:click="changePage(totalPage)"><a href="javascript:void(0)" v-text="totalPage"></a></li>
								<li v-bind:class="{disabled: currentPage == totalPage}" v-on:click="changePage(currentPage + 1)"><a href="javascript:void(0)" aria-label="Next"> <span aria-hidden="true">下一页</span></a></li>
							</ul>
						</nav>
					</div>
				</div>
			</div>
		</div>
	</div>
	<!-- add  Modal -->
	<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">添加用户</h4>
				</div>
				<div class="modal-body">
					<form action="#">
						<div class="form-group">
							<label for="addusername">用户名称</label> <input type="text" id="addusername" class="form-control" placeholder="请输入用户名称" required/>
						</div>
						<div class="form-group">
							<label for="addpassword">用户密码</label> <input type="password" id="addpassword" class="form-control" placeholder="请输入用户密码" required/>
						</div>
						<div class="form-group">
							<label for="addconfirm">确认密码</label> <input type="password" id="addconfirm" class="form-control" placeholder="请输入确认密码" required/>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" onclick="add()">提交</button>
				</div>
			</div>
		</div>
	</div>
	<!-- edit Modal -->
	<div class="modal fade" id="editModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">编辑用户</h4>
				</div>
				<div class="modal-body">
					<form action="#">
						<input type="hidden" id="edituserid" class="form-control" value=""/>
						<div class="form-group">
							<label for="editusername">用户名称</label> <input type="text" id="editusername" class="form-control" placeholder="请输入用户名称" required value=""/>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" onclick="edit()">提交</button>
				</div>
			</div>
		</div>
	</div>
	<jsp:include page="../common/partial/js.jsp"></jsp:include>
	<script type="text/javascript">
		//  请求数据的主体方法
		var userApp = new Vue(
			{
				el : '#userDiv',
				data : {
					users : [],
					count : null,
					currentPage : 1,
					totalPage : null,
					searchName : ""
				},
				mounted : function() {			
					// 穿插一个 全选方法
					$("#checkall").click(function() {
						if (this.checked) {
							$("input[name='id[]']").each(function() {
								this.checked = true;
							})
						} else {
							$("input[name='id[]']").each(function() {
								this.checked = false;
							})
						}
					});

					// 请求数据
					var temp = this;
					$.ajax({
						url : 'api/user/getUsers?pageSize=8&pageIndex=0',
						type : "GET",
						dataType : 'json',
						timeout : 20 * 1000,
						contentType : 'application/json;charset=UTF-8',
						success : function(json) {
							if (json.code == 100) {
								temp.users = json.data.content;
								temp.currentPage = 1;
								temp.count = json.data.totalElements;
							}
						},
						error : function(XMLHttpRequest, textStatus, errorThrown) {
							alert("网络请求错误")
						}
					})
				},
				watch : {
					"count" : function(val, oldVal) {
						this.totalPage = parseInt(val / 8) + (val % 8 > 0 ? 1 : 0);
					}
				},
				methods : {
					search : function() {
						var temp = this;
						$.ajax(
								{
									url : 'api/user/getUsers?pageSize=8&pageIndex=0&username='+ temp.searchName,
									type : "GET",
									dataType : 'json',
									timeout : 20 * 1000,
									contentType : 'application/json;charset=UTF-8',
									success : function(json) {
										if (json.code == 100 && json.data.totalElements > 0) {
											temp.users = json.data.content;
											temp.currentPage = 1;
											temp.count = json.data.totalElements;
										} else {
											alert("你搜索的内容不存在啊")
										}
									},
									error : function(XMLHttpRequest,
											textStatus, errorThrown) {
										//console.log("网络请求错误")
										alert("网络错误")
									},
								})
					},
					changePage : function(p) {
						if (p <= 0) {
							this.currentPage = 1;
						} else if (p > this.totalPage) {
							this.currentPage = this.totalPage;
						} else {
							this.currentPage = p;
						}
						this.submit(this.currentPage);
					},
					submit : function(page) {
						if (!page) {
							page = 1;
						}
						var temp = this;
						$.ajax({
							url : 'api/user/getUsers?pageSize=8&pageIndex='+ (page - 1),
							type : 'GET',
							dateType : 'json',
							timeout : 20 * 1000,
							contentType : 'application/json;charset=UTF-8',
							success : function(json) {
								if (json.code == 100) {
									temp.users = json.data.content;
									temp.currentPage = page;
								}
							}
						})
					},
					toggleY:function(){
						$("[data-toggle='tooltip']").tooltip();
					}
				}
			})
		
        // 单个删除
        function del(id) {
            //询问框
            layer.confirm('您确定要删除吗?', {
                shade: false,
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.ajax({
                    type: 'POST',
                    url: 'api/user/delete',
                    data: { id: id },
                    dataType: 'json',
                    success: function (result) {
                        if (result != null && result.code > 100) {
                            layer.msg(result.msg, { icon: 0, shift: 4, time: 1000 })
                        } else {
                            layer.msg(result.msg, { icon: 6, shift: 4, time: 1000 });
                            setTimeout(function () {
                                window.location.reload();
                            }, 1000);
                        }
                    }
                });
            }, function () {

            });
        }

        //批量删除
        function DelSelect() {
            var becheckbox = '[';
            $("input[name='id[]']").each(function () { //遍历table里的全部checkbox
                if (this.checked == true) //如果被选中
                    becheckbox += $(this).val() + ","; //获取被选中的值
            });
            if (becheckbox.length > 1) { //如果获取到
                becheckbox = becheckbox.substring(0, becheckbox.length - 1); //把最后一个逗号去掉
                becheckbox += ']';
                //询问框
                layer.confirm('您确定要删除所有选中项吗?', {
                    shade: false,
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    $.ajax({
                        type: 'POST',
                        url: 'api/user/deleteAll',
                        data: { ids: becheckbox },
                        dataType: 'json',
                        success: function (result) {
                            if (result != null && result.code > 100) {
                                layer.msg(result.msg, { icon: 0, shift: 4, time: 1000 })
                            } else {
                                layer.msg(result.msg, { icon: 6, shift: 4, time: 1000 });
                                setTimeout(function () {
                                    window.location.reload();
                                }, 1000);
                            }
                        }
                    });
                }, function () {

                });
            } else {
                layer.msg("请至少选中一项！", { icon: 0, shift: 6, time: 1000 })
            }
        }
    
        // 模态添加
        function add() {
            var UserName = document.getElementById("addusername").value;
			var PassWord = document.getElementById("addpassword").value;
			var Confrim = document.getElementById("addconfirm").value;
            if(UserName =='')
            {
                layer.msg('用户名称不能为空！', { icon: 0, shift: 6, time: 1000 });
                return;
            }
            if(PassWord =='')
            {
                layer.msg('用户密码不能为空！', { icon: 0, shift: 6, time: 1000 });
                return;
            }
            if(Confrim =='')
            {
                layer.msg('确认密码不能为空！', { icon: 0, shift: 6, time: 1000 });
                return;
            }
            if(Confrim != PassWord)
            {
                layer.msg('两次密码不一致！', { icon: 0, shift: 6, time: 1000 });
                return;
            }

            $.ajax({
                type: 'POST',
                url: 'api/user/add',
                data: { username:UserName,password:PassWord,confrim:Confrim },
                dataType: 'json',
                success: function (result) {
                    $('#addModal').modal('hide');
                    if (result != null && result.code > 100) {
                        layer.msg(result.msg, { icon: 0, shift: 6, time: 1000 });
                    } else {
                        layer.msg(result.msg, { icon: 6, shift: 4, time: 1000 });                       
                        setTimeout(function () {
                            window.location.reload();
                        }, 1000);
                    }
                }
            });
        }

        // 模态修改
        function editInfo(id) {
            var Id = document.getElementById("table").rows[id].cells[0].firstChild.value;
            var UserName = document.getElementById("table").rows[id].cells[1].innerText;   
            //alert(Id+":"+UserName);
            
            $("#edituserid").val(Id.trim());           
            $("#editusername").val(UserName.trim());

            $('#editModal').modal('show');
        }

        // 修改后提交
        function edit() {
            var Id = document.getElementById("edituserid").value;
            var UserName = document.getElementById("editusername").value;

            if(UserName =='')
            {
                layer.msg('用户名称不能为空！', { icon: 0, shift: 6, time: 1000 });
                return;
            }
            
            $.ajax({
                type: 'POST',
                url: 'api/user/edit',
                data: { username:UserName, id: Id },
                dataType: 'json',
                success: function (result) {
                    $('#editModal').modal('hide');
                    if (result != null && result.code > 100) {
                        layer.msg(result.msg, { icon: 0, shift: 6, time: 1000 })
                    } else {
                        layer.msg(result.msg, { icon: 6, shift: 4, time: 1000 });
                        setTimeout(function () {
                            window.location.reload();
                        }, 1000);
                    }
                }
            });
        }
        
        // 重置密码
        function reset(id) {
            //询问框
            layer.confirm('您确定要初始化该账户吗?', {
                shade: false,
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.ajax({
                    type: 'POST',
                    url: 'api/user/reset',
                    data: { id: id,password:'123456' },
                    dataType: 'json',
                    success: function (result) {
                        if (result != null && result.code > 100) {
                            layer.msg(result.msg, { icon: 0, shift: 6, time: 1000 })
                        } else {
                            layer.msg(result.msg, { icon: 6, shift: 4, time: 1000 });
                            setTimeout(function () {
                                window.location.reload();
                            }, 1000);
                        }
                    }
                });
            }, function () {

            });
        }
	</script>
</body>
</html>
